package logic.xml.parser;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;

import logic.bean.TOCItem;


public class NCXHandler
        extends
        DefaultHandler
{
	private NavPoint           curentNavPoint = null;
	private ArrayList<String>  navLabels;
	HashMap<String, String>    map;
	private ArrayList<TOCItem> navPointList;
	private String             preTag;
	
	StringBuffer               buf            = new StringBuffer();
	private String             currentLabel = "";
	
	public ArrayList<TOCItem> getNavPointList() {
		return this.navPointList;
	}
	
	public ArrayList<String> getNavLabels() {
		return navLabels;
	}
	
	public HashMap<String, String> getMaps() {
		return map;
	}
	
	@Override
	public void startDocument() throws SAXException {
		this.navPointList = new ArrayList<TOCItem>();
		navLabels = new ArrayList<String>();
		map = new HashMap<String, String>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if ("navPoint".equals(qName))
		{
			curentNavPoint = new NavPoint();
			 currentLabel = "";
			if (attributes.getLength() ==1) curentNavPoint.setId(attributes.getValue(0));
			else if(attributes.getLength() ==2){
				curentNavPoint.setId(attributes.getValue(0));
				curentNavPoint.setPlayOrder(attributes.getValue(1));
				
			}
		}
		else if ("navLabel".equals(qName))
		{
			preTag = qName;
		}
		else if ("text".equals(qName))
		{
			preTag = qName;
		}
		else if ("content".equals(qName))
		{
			curentNavPoint.setContentSrc(attributes.getValue(0));
		}
		
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (curentNavPoint != null && preTag != null)
		{
			String content = new String(ch, start, length);
			if ("text".equals(preTag))
			{
				//curentNavPoint.setNavLabel(content);
				currentLabel += content;
			}
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (curentNavPoint != null)
		{
			if ("navPoint".equals(qName))
			{
				curentNavPoint.setNavLabel(currentLabel);
				navLabels.add(currentLabel);
				navPointList.add(curentNavPoint);
				map.put(curentNavPoint.getNavLabel(), curentNavPoint.getId());
				curentNavPoint = null;
				preTag = null;
			}
		}		
	}
}
